import { createApi } from 'kuan-request'
import authority from '../authority'
import { login401 } from '@/utils/login'
import encrypt from './encrypt' // 加密对接

const request = createApi({
  // loadingCtrl: () => {}, // 自定义loading
  // toast: () => {}, // 自定义提示
  getHeaders: config => {
    const { params = {}, data = {} } = config
    const now = Date.parse(new Date()) / 1000
    const headers = {
      'X-Halo-App': 'wedding-h5',
      'X-Halo-Region': '', // todo
      'Http-Request-Halo-Time': now,
      'Http-Request-Halo-Sign': encrypt({ ...params, ...data, time: now })
    }
    const {token = ''} = authority.get() || {}
    if (token) {
      headers.Authorization = `Bearer ${token}`
    }
    return headers
  },
  handleError: (status, msg) => {
    console.log(`${status ? status + ':' : ''}${msg}`)
    if (status === 401) login401()
  }
})

export default request
